'use strict';

angular.module('xianwan', [
        'ui.router',
        'ngResource',
        'ngFileUpload',
        'luegg.directives',
        'ngMessages'
    ])
    .config(function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('main', {
                url: '/',
                templateUrl: 'templates/main.html',
                controller: 'MainController'
            })
        $urlRouterProvider.otherwise('/');
    })
    .config(function($httpProvider) {
        $httpProvider.interceptors.push('authInterceptor');
    })
    .factory('authInterceptor', function(Constant, LocalStorage, NW) {

        let logout = function () {
            NW.resetStatus();
            window.location = window.location.href.substring(0, window.location.href.indexOf(window.location.hash));
        }

        let dateFormat = function (date) {
            let arr1 = [date.getFullYear(), lengthFormat(date.getMonth() + 1), lengthFormat(date.getDate())];
            let arr2 = [lengthFormat(date.getHours()), lengthFormat(date.getMinutes()), lengthFormat(date.getSeconds())];
    
            return arr1.join('-') + ' ' + arr2.join(':');
        }

       let lengthFormat = function (num) {
            return (String(num).length === 1) ? ('0' + num) : num;
        }

        function fileSizeCheck(logPath) {
            const fs = require('fs');
    
            try {
                if (fs.statSync(logPath).size >= 2 * 1024 * 1024) {
                    fs.unlinkSync(logPath);
                    console.log('日志文件已超出限制，成功删除本地日志文件');
                }
            } catch (e) {
                // 
            }
        }

        let logError = function (date, url, response) {
            let fs = require('fs');
            let path = require('path');
            let dataPath = require('nw.gui').App.dataPath;
            let logPath = path.join(dataPath, 'log.txt');

            fileSizeCheck(logPath);

            fs.open(logPath, 'wx', function (err, callback) {
                if (err) {
                    if (err.code === 'EEXIST') {
                        fs.appendFileSync(logPath, '\t\n');
                        fs.appendFileSync(logPath, '\t\n');
                        fs.appendFileSync(logPath, dateFormat(date));
                        fs.appendFileSync(logPath, '\t\n');
                        fs.appendFileSync(logPath, url);
                        if (response) {
                            fs.appendFileSync(logPath, '\t\n');
                            fs.appendFileSync(logPath, response);
                        }
                        return;
                    }
    
                    throw err;
                }
                
                fs.appendFileSync(logPath, dateFormat(date));
                fs.appendFileSync(logPath, '\t\n');
                fs.appendFileSync(logPath, url);
                if (response) {
                    fs.appendFileSync(logPath, '\t\n');
                    fs.appendFileSync(logPath, response);
                }
            });
        }

        return {

            request: function(config) {
                config.url = config.url.replace(/\/\?/g, '?');
                return config
            },

            response: function(response) {
            	
                if (response.config.url.indexOf('qr-token') > -1) {
                    return response;
                }
                if (response.data.status === Constant.TOKEN_NOT_FOUND || response.data.status === Constant.TOKEN_EXPIRED) {
                    logError(new Date(), response.config.url, response);
                    LocalStorage.save(Constant.LOGOUT_OPERATION, '认证过期, 请重新登陆!');
				   
					/* 认证过期时，清除当前用户密码，保留 记住密码和自动登录选中状态 */
                    let AUTO_LOGIN_INFO = 'AUTO_LOGIN_INFO';
                    let autoLoginInfo = LocalStorage.get(AUTO_LOGIN_INFO);

                    if (autoLoginInfo) {
                        delete autoLoginInfo.token;

                        LocalStorage.save(AUTO_LOGIN_INFO, autoLoginInfo);
                    }
                    logout();
                }
                if (response.data.status === Constant.TOKEN_MISSING) {
                    logError(new Date(), response.config.url, response);
                    console.log('Token Missing:', response.config.url);
                    
                    return response;
                }
                if (response.data.status === Constant.LICENSE_NOT_FOUND || response.data.status === Constant.LICENSE_INVALID) {
                    logError(new Date(), response.config.url, response);
                    LocalStorage.save(Constant.LOGOUT_OPERATION, '应用正在维护, 请联系管理员!');
                    logout();
                }

                logError(new Date(), response.config.url);
                return response;
            }

        };
    })
    .run(['$rootScope', function ($rootScope) {
        /* $safeApply to execute $scope.$apply without error: $apply already in progress */
        $rootScope.$safeApply = function (fn, scope) {
            fn = fn || function () {};
            scope = scope || this;

            if (scope.$$phase) {
                fn();
            } else {
                scope.$apply(fn);
            }
        };
    }])
    .run(['$rootScope', 
        function ($rootScope) {
            $rootScope.commonConfig = {
                isShowScreenShot: true
            };

            const os = require('os');
            let clientInfo = {
                platform: os.platform(), 
                release: os.release()
            };

            if (clientInfo.platform.indexOf('win') > -1 
                && parseInt(clientInfo.release) < 6) {
                /* windows xp */
                $rootScope.commonConfig.isXpOS = true;
            }
        }
    ])
    .run(['$rootScope', 
        function ($rootScope) {
            let preloadImages = function (imagesArr) {
                if (!preloadImages.list) {
                    preloadImages.list = [];
                }

                let list = preloadImages.list;
                for (let i = 0; i < imagesArr.length; i++) {
                    let img = new Image();
                    img.onload = function () {
                        let index = list.indexOf(this);
                        if (index !== -1) {
                            // remove image from the array once it's loaded
                            // for memory consumption reasons
                            list.splice(index, 1);
                        }
                    };
                    list.push(img);
                    img.src = imagesArr[i];
                }
            };
            preloadImages([
                'images/default_person_avatar.png', 
                'images/default_group_avatar.png', 
                'tray@2x.png', 
                'tray_active@2x.png'
            ]);
        }
    ]);
